package cn.xing.interceptor;

import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.xing.dao.LoginTicketDAO;
import cn.xing.dao.UserDAO;
import cn.xing.model.HostHolder;
import cn.xing.model.LoginTicket;
import cn.xing.model.User;

/**
 * 登录拦截器，拦截Controller，获取已登录用户信息
 * 
 * @author Xing
 *
 */
@Component
public class PassportInterceptor implements HandlerInterceptor {

	@Autowired
	private LoginTicketDAO loginTicketDAO;

	@Autowired
	private UserDAO userDAO;

	@Autowired
	private HostHolder hostHolder;

	// 请求处理之前
	@Override
	public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o)
			throws Exception {
		String ticket = null;
		if (httpServletRequest.getCookies() != null) {
			for (Cookie cookie : httpServletRequest.getCookies()) {
				if (cookie.getName().equals("ticket")) {
					ticket = cookie.getValue();
					break;
				}
			}
		}

		if (ticket != null) {
			LoginTicket loginTicket = loginTicketDAO.selectByTicket(ticket);
			if (loginTicket == null || loginTicket.getExpired().before(new Date()) || loginTicket.getStatus() != 0) {
				return true;
			}
			// ticket有效
			User user = userDAO.selectById(loginTicket.getUserId());
			hostHolder.setUser(user);
		}
		return true;
	}

	// 请求处理之后，视图返回之前
	@Override
	public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
			ModelAndView modelAndView) throws Exception {
		if (modelAndView != null && hostHolder.getUser() != null) {
			// 渲染页面需要
			modelAndView.addObject("user", hostHolder.getUser());
		}
	}

	// 视图返回之后
	@Override
	public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
			Object o, Exception e) throws Exception {
		hostHolder.clear();
	}
}
